package com.mjlf.mjatis.util;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.java.Log;

import java.lang.reflect.Field;
import java.util.Set;

/**
 * @ClassName Json2Entity
 * @Author mjlft
 * @Date 2020/5/29 22:17
 * @Version 1.0
 * @Description json转换为实体类
 */
@Log
public final class Json2Entity {

    /**
     * 将json对象转换为需要类类实例
     * @param json
     * @param tClass
     * @param <T>
     * @return
     */
    public static <T> T getEntity(JSONObject json, Class<T> tClass) throws IllegalAccessException, InstantiationException {
        T t = tClass.newInstance();

        Set<String> keys = json.keySet();
        keys.stream().forEach(key -> {
            try {
                Field field = tClass.getDeclaredField(key);
                if(field != null){
                    field.setAccessible(true);
                    Class type = field.getType();
                    if(type == Integer.class){
                        field.setInt(t, json.getInteger(key));
                    }else if(type == String.class){
                        field.set(t, json.getString(key));
                    }else if(type == Boolean.class){
                        field.setBoolean(t, json.getBoolean(key));
                    }else {
                        field.set(t, json.get(key));
                    }
                }else {
                    log.info(tClass.getName() + "类中不存在属性" + key);
                }
            } catch (NoSuchFieldException e) {
                log.info(tClass.getName() + "找不到属性" + key);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        });
        return t;
    }
}
